import { _decorator, Component, EditBox, Label, log, Node, ScrollView } from 'cc';
// import * as WebSocket from 'ws';
import { ProtobufWebSocketClient } from './ProtobufWebSocketClient';
// import proto from '../../Proto.js/proto.js'
const { ccclass, property } = _decorator;

@ccclass('WebSoketScript3')
export class WebSoketScript3 extends Component {
    
    @property(EditBox)
    private textNode: EditBox = null;

    @property(Label)
    private ChatFrame: Label = null;

    @property(ScrollView)
    private scrollView: ScrollView = null;
    
    // 使用客户端
    private client:ProtobufWebSocketClient = null;
    
    start() {
        this.ChatFrame.getComponent(Label).string = '';

        // this.client = new ProtobufWebSocketClient('ws://127.0.0.1:6577/websocket', this.ChatFrame.getComponent(Label));
        this.client = new ProtobufWebSocketClient('ws://192.168.0.105:6577/websocket', this.ChatFrame.getComponent(Label));

        // let palayer: proto.PlayerInfo = new proto.PlayerInfo();
        // palayer.userId = 100;
        // palayer.gender = 1;
        // palayer.userName = "zhangsan";
        // palayer.nickName = "帅哥";
        // console.log('palayer', palayer)


        // let chatMessage: proto.ChatMessage = new proto.ChatMessage();
        // chatMessage.sender = '私聊';
        // chatMessage.messageText = 'hello';
        // chatMessage.timestamp = 123456789;
        // console.log('chatMessage', chatMessage)


        // let proto = new ProtobufWebSocketClient();

        // log('proto', proto)

        // proto.show()
        
        // const userToSend :proto.chatMessage = new proto.chatMessage();
        // log('userToSend', userToSend)
        
    }

    update(deltaTime: number) {
        
    }

    // 自定义函数处理私聊消息
    handlePrivateMessage(message) {
        console.log(`Received private message from ${message.from}: ${message.content}`);
        this.ChatFrame.getComponent(Label).string += '\n' + message.content;
    }

    // 自定义函数处理群聊消息
    handleGroupMessage(message) {
        console.log(`Received group message: ${message.content}`);
    }

    sendMessage() {
        // let message = this.textNode.getComponent(EditBox).string;

        // const userToSend :ChatMessage.chatMessage = new ChatMessage.chatMessage();
        // userToSend.setId(123);
        // userToSend.setName('John Doe');
        // userToSend.setEmail('john.doe@example.com');

        // this.socket.sendMessage(userToSend);

        if (this.client.socket.readyState === WebSocket.OPEN) {
            let message = this.textNode.getComponent(EditBox).string;
            log("发送消息：" + message);

            var customMessage = {
                type: 'private',
                from: 'user1',
                to: 'user2',
                content: message
            };
            // this.client.sendMessage(JSON.stringify(customMessage));
            this.client.sendMessage(message);
            this.scrollView.scrollToBottom(0.2);
        }
    }
}


